package bar.dark.lee.budget;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import bar.dark.lee.BDConstents;
import bar.dark.lee.R;
import bar.dark.lee.SuperActivity;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.CalendarPickerDialog;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.EditTextInputFilter;
import bar.dark.lee.common.RadioDialogActivity;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.setting.TipInfoActivity;
import bar.dark.lee.setting.TipsActivity;

public class BudgetUpdateActivity extends SuperActivity
{
	private static final int REQUEST_CATEGORY = 0;
	
	private DBSQLite sql;
	
	private View dateView;
	private TextView dateTextView;
	
	private View categoryView;
	private TextView categoryTextView;
	
	private EditText moneyEditText;
	
	private Button deleteButton;
	private Button updateButton;
	
	private ArrayList<String> categoryList = null;
	private ArrayList<BudgetData> budgetList = null;
	
	private BudgetData data;
	
	private int toYear;
	private int toMonth;
	
	private int flag;
	
	private String tableName;
	private String categoryTableName;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		sql = DBSQLite.getInstance(superContext);
		
		setContentView(R.layout.budget_update_activity);
		
		Intent intent = getIntent();
		flag = intent.getIntExtra(BudgetTabActivity.BUDGET_FLAG, 0);
		
		if (flag == BudgetTabActivity.OUT_FLAG)
		{
			setTitle("지출 예산 수정");
			tableName = "budget_category";
			categoryTableName = "category_out_list";
		}
		else if (flag == BudgetTabActivity.IN_FLAG)
		{
			setTitle("수입 예산 수정");
			tableName = "budget_in_category";
			categoryTableName = "category_in_list";
		}
		else if (flag == BudgetTabActivity.MOVE_FLAG)
		{
			setTitle("이동 예산 수정");
			tableName = "budget_move_category";
			categoryTableName = "category_move_list";
		}
		
		setFindView();
		setOnClickListener();
		new ShowDialog().execute(BDUtil.asyncFlag, 0);
	}

	private void setFindView()
	{
		dateView = findViewById(R.id.budgetUpdateDateView);
		dateTextView = (TextView) findViewById(R.id.budgetUpdateDateTextView);
		
		categoryView = findViewById(R.id.budgetUpdateCategoryView);
		categoryTextView = (TextView) findViewById(R.id.budgetUpdateCategoryTextView);
		
		moneyEditText = (EditText) findViewById(R.id.budgetUpdateMoneyEditText);
		EditTextInputFilter.filteringMoneyEditText(moneyEditText);
		
		deleteButton = (Button) findViewById(R.id.budgetDeleteButton);
		updateButton = (Button) findViewById(R.id.budgetUpdateButton);
	}
	
	private void setOnClickListener()
	{
		dateView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
//				// 다이얼로그 날짜를 뺀다.
//				try {  
//					DatePickerDialog dialog = 
//							new DatePickerDialog(superContext, new OnDateSetListener()
//							{
//								@Override
//								public void onDateSet(DatePicker view, int year, int monthOfYear,
//										int dayOfMonth)
//								{
//									toYear = year;
//									toMonth = monthOfYear;
//									
//									dateTextView.setText(toYear + "년 " + (toMonth+1) + " 월");
//								}
//							}, toYear, toMonth, 1);         
//					
//					// 다이얼로그에서 날짜 빼고 나오는 로직
//					Field[] f = dialog.getClass().getDeclaredFields();  
//					
//					for (Field dateField : f) 
//					{   
//						if(dateField.getName().equals("mDatePicker")) 
//						{    
//							dateField.setAccessible(true);             
//							DatePicker datePicker = (DatePicker)dateField.get(dialog); 
//							Field datePickerFields[] = dateField.getType().getDeclaredFields();
//							
//							for(Field datePickerField : datePickerFields) 
//							{     
//								if("mDayPicker".equals(datePickerField.getName())) 
//								{      
//									datePickerField.setAccessible(true);     
//									Object dayPicker = new Object();      
//									dayPicker = datePickerField.get(datePicker);      
//									((View)dayPicker).setVisibility(View.GONE);     
//								}    
//							}   
//						}  
//					}         
//					
//					dialog.show();       
//					
//				} catch (IllegalArgumentException e) 
//				{ 
//					e.printStackTrace(); 
//				} catch (IllegalAccessException e) 
//				{  
//					e.printStackTrace(); 
//				}
				
				CalendarPickerDialog cpd = new CalendarPickerDialog(superContext, new CalendarPickerDialog.ICalendarPickerDateSetListener() {
					@Override
					public void onDateSet(int year, int monthOfYear, int dayOfMonth) {
						
						toYear = year;
						toMonth = monthOfYear;
						
						dateTextView.setText(toYear + "년 " + (toMonth+1) + " 월");
					}
				}, toYear, toMonth, 1);
				
				cpd.show();
			}
		});
		
		categoryView.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent(superContext, RadioDialogActivity.class);
				intent.putExtra(RadioDialogActivity.RADIODATA, categoryList);
				intent.putExtra(RadioDialogActivity.RADIOSELECT, categoryTextView.getText().toString());
				
				if (flag == BudgetTabActivity.OUT_FLAG)
				{
					intent.putExtra(RadioDialogActivity.RADIOTYPE, RadioDialogActivity.CATEGORY_OUT_TYPE);
					intent.putExtra(RadioDialogActivity.RADIOBUTTONSTRING, RadioDialogActivity.CATEGORY_OUT_TYPE_STRING);
				}
				else if (flag == BudgetTabActivity.IN_FLAG)
				{
					intent.putExtra(RadioDialogActivity.RADIOTYPE, RadioDialogActivity.CATEGORY_IN_TYPE);
					intent.putExtra(RadioDialogActivity.RADIOBUTTONSTRING, RadioDialogActivity.CATEGORY_IN_TYPE_STRING);
				}
				else if (flag == BudgetTabActivity.MOVE_FLAG)
				{
					intent.putExtra(RadioDialogActivity.RADIOTYPE, RadioDialogActivity.CATEGORY_MOVE_TYPE);
					intent.putExtra(RadioDialogActivity.RADIOBUTTONSTRING, RadioDialogActivity.CATEGORY_MOVE_TYPE_STRING);
				}
				
				startActivityForResult(intent, REQUEST_CATEGORY);
			}
		});
		
		updateButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (categoryTextView.equals("없음"))
				{
					BDUtil.showDialog(superContext, "경고", "카테고리가 없습니다.");
					return;
				}
				
				if (BDUtil.getCommaDel(moneyEditText.getText().toString()).equals("") 
						|| BDUtil.getCommaDel(moneyEditText.getText().toString()).equals("0"))
				{
					BDUtil.showDialog(superContext, "경고", "금액을 정확히 입력해 주세요.");
					return;
				}
				
				int year = toYear;
				int month = toMonth+1;
				
				String date = "";
				
				if (month < 10)
				{
					date = year + "0" + month;
				}
				else
				{
					date = year + "" + month;
				}
				
				if (!data.getCount().equals(date) || 
						!data.getName().equals(categoryTextView.getText().toString()))
				{
					budgetList = new ArrayList<BudgetData>();
					
					sql.selectMapTile(superContext, "SELECT * FROM " + tableName +
							" WHERE name = '" + BDUtil.getApostrophe(categoryTextView.getText().toString()) + "'" +
							" and count = " + date + ";", 
							new ParseSelectData()
					{
						@Override
						public void resultData(Cursor c)
						{
							int idIdx = c.getColumnIndex("id");
							int nameIdx = c.getColumnIndex("name");
							int moneyIdx = c.getColumnIndex("money");
							int countIdx = c.getColumnIndex("count");
							int linkidIdx = c.getColumnIndex("linkid");
							
							c.moveToFirst();
							
							for (int i = 0; i < c.getCount(); i++)
							{
								BudgetData data = new BudgetData();
								
								data.setId(c.getInt(idIdx) + "");
								data.setName(c.getString(nameIdx));
								data.setMoney(c.getString(moneyIdx));
								data.setCount(c.getString(countIdx));
								data.setLinkid(c.getString(linkidIdx));
								
								budgetList.add(data);
								c.moveToNext();
							}
						}
					});
					
					if (budgetList.size() > 0)
					{
						BDUtil.showDialog(superContext, "경고", "이미 예산이 등록된 카테고리 입니다.");
						return;
					}
				}
				
				new ShowDialog().execute(BDUtil.asyncFlag, 1);
			}
		});
		
		deleteButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				BDUtil.showSelectDialog(superContext, "경고", "정말로 삭제 하시겠습니까?", 
				new DialogInterface.OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						new ShowDialog().execute(BDUtil.asyncFlag, 2);
						dialog.dismiss();
					}
				});
			}
		});
	}
	
	private void setData()
	{
		Intent intent = getIntent();
		String id = intent.getStringExtra(BudgetListActivity.BUDGET_ID);
		
		sql.selectMapTile(superContext, "SELECT * FROM " + tableName + " WHERE id = " +
				id + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int moneyIdx = c.getColumnIndex("money");
				int countIdx = c.getColumnIndex("count");
				int linkidIdx = c.getColumnIndex("linkid");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					data = new BudgetData();
					
					data.setId(c.getInt(idIdx) + "");
					data.setName(c.getString(nameIdx));
					data.setMoney(c.getString(moneyIdx));
					data.setCount(c.getString(countIdx));
					data.setLinkid(c.getString(linkidIdx));
					
					c.moveToNext();
				}
			}
		});
		
		sql.selectMapTile(this, "SELECT kind FROM " + categoryTableName + " ORDER BY count DESC", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				categoryList = new ArrayList<String>();
				
				int nameIndex = c.getColumnIndex("kind");
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					String kind = c.getString(nameIndex);
					categoryList.add(kind);
					c.moveToNext();
				}
				
				if (flag == BudgetTabActivity.OUT_FLAG)
				{
					categoryList.add(BDConstents.CATEGORY_USE_CARD);
					categoryList.add(BDConstents.CATEGORY_FAN_OUT_MONEY);
					categoryList.add(BDConstents.CATEGORY_FAN_IN_CHECK);
					categoryList.add(BDConstents.CATEGORY_SUSUMONEY);
					categoryList.add(BDConstents.CATEGORY_POST_OUT);
				}
				else if (flag == BudgetTabActivity.IN_FLAG)
				{
					categoryList.add(BDConstents.CATEGORY_FAN_IN_MONEY);
					categoryList.add(BDConstents.CATEGORY_FAN_OUT_CHECK);
				}
				else if (flag == BudgetTabActivity.MOVE_FLAG)
				{
					categoryList.add(BDConstents.CATEGORY_OUT_CARD);
					categoryList.add(BDConstents.CATEGORY_IN_CARD);
					categoryList.add(BDConstents.CATEGORY_OUT_BANK);
					categoryList.add(BDConstents.CATEGORY_IN_BANK);
				}
				
				if (categoryList.size() < 1)
				{
					String memo = "없음";
					categoryList.add(memo);
					categoryView.setClickable(false);
				}
				
				categoryTextView.setText(categoryList.get(0).toString());
			}
		});
	}
	
	private void setUpdateData()
	{
		HashMap<String, String> map = new HashMap<String, String>();
		
		map.put("name", categoryTextView.getText().toString());
		map.put("money", BDUtil.getCommaDel(moneyEditText.getText().toString()));
		
		int year = toYear;
		int month = toMonth+1;
		
		if (month < 10)
		{
			map.put("count", year + "0" + month);
		}
		else
		{
			map.put("count", year + "" + month);
		}
		
		String [] whereArgs = new String[]{data.getId()};
		
		sql.update(superContext, tableName, map, "id = ?", whereArgs);
	}
	
	private void setDeleteData()
	{
		String [] whereArgs = new String[]{data.getId()};
		sql.delete(superContext, tableName, "id = ?", whereArgs);
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode == REQUEST_CATEGORY)
		{
			if (resultCode == Activity.RESULT_OK)
			{
				String selectData = data.getStringExtra(RadioDialogActivity.RADIOSTRING);
				categoryTextView.setText(selectData);
			}
			else if (resultCode == RadioDialogActivity.REFRESH_CATEGORY)
			{
				final String beforeCategory = categoryTextView.getText().toString();
				
				sql.selectMapTile(this, "SELECT kind FROM " + categoryTableName + " ORDER BY count DESC", new ParseSelectData()
				{
					@Override
					public void resultData(Cursor c)
					{
						categoryList = new ArrayList<String>();
						
						int nameIndex = c.getColumnIndex("kind");
						c.moveToFirst();
						
						for (int i = 0; i < c.getCount(); i++)
						{
							String kind = c.getString(nameIndex);
							categoryList.add(kind);
							c.moveToNext();
						}
						
						if (categoryList.size() < 1)
						{
							String memo = "없음";
							categoryList.add(memo);
							categoryView.setClickable(false);
						}
						
						categoryTextView.setText(beforeCategory);
					}
				});
			}
		}
	}

	/**
	 * 다이얼로그 뛰우기 
	 */
	private class ShowDialog extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			if (BDUtil.btnEnable)
			{
				BDUtil.btnEnable = false;
				BDUtil.asyncFlag = -1;
				
				dialog = new ProgressDialog(superContext);
				dialog.setCancelable(false);
				dialog.setMessage("Loading...");
				dialog.show();
			}
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			if (arg0[0] == 0) 
			{
				if (arg0[1] == 0)
				{
					setData();
					
					return arg0[1];
				}
				if (arg0[1] == 1)
				{
					try
					{
						sql.beginTansaction(superContext);
						
						setUpdateData();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				if (arg0[1] == 2)
				{
					try
					{
						sql.beginTansaction(superContext);
						
						setDeleteData();
						
						sql.setTransactionSuccessful();
					} catch (Exception e)
					{
						return -1;
					} finally {
						try 
						{
							sql.endTransaction(superContext);
						} catch (Exception e) 
						{
							return -1;
						}
					}
					
					return arg0[1];
				}
				
				return arg0[0];
			}
			else
			{
				return arg0[0];
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);

			if (dialog != null) {
				dialog.dismiss();
			}
			
			if (result == -1)
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				BDUtil.showDialog(superContext, "오류", "데이터 저장에 실패했습니다.");
			}
			else if (result == 0) 
			{
				BDUtil.btnEnable = true;
				BDUtil.asyncFlag = 0;
				
				String date = data.getCount();
				
				String year = date.substring(0, 4);
				String month = date.substring(4, date.length());
				
				toYear = Integer.parseInt(year);
				toMonth = Integer.parseInt(month)-1;
				
				dateTextView.setText(toYear + "년 " + (toMonth+1) + " 월");
				
				categoryTextView.setText(data.getName());
				moneyEditText.setText(data.getMoney());
			}
			else if (result == 1)
			{
				BDUtil.showDialogFinish(superContext, "확인", "수정이 완료 되었습니다.");
			}
			else if (result == 2)
			{
				BDUtil.showDialogFinish(superContext, "확인", "삭제가 완료 되었습니다.");
			}
		}
	}
	
	@Override
	protected void tipButton()
	{
		Intent intent = new Intent(this, TipInfoActivity.class);
		intent.putExtra(TipsActivity.TIP_REQUEST_KEY, TipsActivity.TIP_BUDGET);
		startActivity(intent);
	}

}
